package test.hello.utils;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SftpUtils2 {

	public static ChannelSftp createSftpConnection(String host, int port, String userName, String password) throws Exception {
		JSch jsch = new JSch();
		Session session = createSession(jsch, host, port, userName);
		session.setPassword(password);
		session.connect();
		Channel channel = session.openChannel("sftp");
		channel.connect();
		return (ChannelSftp) channel;

	}

	private static Session createSession(JSch jsch, String host, int port, String userName) throws Exception {
		Session session = null;
		if (port <= 0) {
			session = jsch.getSession(userName, host);
		} else {
			session = jsch.getSession(userName, host, port);
		}
		if (session == null) {
			throw new Exception(host + " session is null");
		}
		session.setConfig("StrictHostKeyChecking", "no");
		return session;
	}

	public static void disconnect(ChannelSftp sftp) {
		try {
			if (sftp != null) {
				if (sftp.isConnected()) {
					sftp.disconnect();
				}
				if (null != sftp.getSession()) {
					sftp.getSession().disconnect();
				}
			}
		} catch (JSchException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
	}
}